package com.bookcloud.java21.aitools;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.*;

/** Historical Sign-in Query UI Panel 学生历史签到查询界面 */
public class HistorySignUI extends JPanel {

  private JComboBox<String> dateSelector;
  private JLabel titleLabel;
  private JPanel signedStudentsPanel;
  private JPanel unsignedStudentsPanel;
  private JLabel statisticsLabel;

  // Color constants for student name display
  private static final Color SIGNED_BG_COLOR = new Color(144, 238, 144); // Light green
  private static final Color UNSIGNED_BG_COLOR = new Color(255, 182, 193); // Light pink
  private static final Color SIGNED_TEXT_COLOR = new Color(0, 100, 0); // Dark green
  private static final Color UNSIGNED_TEXT_COLOR = new Color(139, 0, 0); // Dark red

  public HistorySignUI() {
    initializeComponents();
    layoutComponents();
    loadHistoricalData();
    setupEventHandlers();
  }

  /** Initialize all UI components 初始化所有UI组件 */
  private void initializeComponents() {
    // Create date selector
    dateSelector = new JComboBox<>();
    populateDateSelector();
    dateSelector.setFont(new Font("微软雅黑", Font.PLAIN, 14));
    dateSelector.setPreferredSize(new Dimension(150, 30));

    // Create title label
    titleLabel = new JLabel();
    titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
    titleLabel.setHorizontalAlignment(JLabel.CENTER);
    titleLabel.setForeground(new Color(70, 130, 180));

    // Create panels for signed and unsigned students
    signedStudentsPanel = new JPanel();
    unsignedStudentsPanel = new JPanel();

    // Create statistics label
    statisticsLabel = new JLabel();
    statisticsLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
    statisticsLabel.setHorizontalAlignment(JLabel.CENTER);
    statisticsLabel.setForeground(new Color(255, 140, 0)); // Orange color
  }

  /** Populate date selector with recent dates 填充日期选择器 */
  private void populateDateSelector() {
    // Add recent dates (last 30 days)
    LocalDate today = LocalDate.now();
    for (int i = 0; i < 30; i++) {
      LocalDate date = today.minusDays(i);
      String dateStr = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
      dateSelector.addItem(dateStr);
    }

    // Set default to show 2025-06-13 as in the prototype
    dateSelector.setSelectedItem("2025-06-13");
  }

  /** Layout all components 布局所有组件 */
  private void layoutComponents() {
    setLayout(new BorderLayout());
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    setBackground(Color.WHITE);

    // Top panel with date selector
    add(createTopPanel(), BorderLayout.NORTH);

    // Center panel with student lists
    add(createCenterPanel(), BorderLayout.CENTER);

    // Bottom panel with statistics
    add(createBottomPanel(), BorderLayout.SOUTH);
  }

  /** Create top panel with date selector 创建顶部面板，包含日期选择器 */
  private JPanel createTopPanel() {
    JPanel topPanel = new JPanel(new BorderLayout());
    topPanel.setBackground(Color.WHITE);
    topPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));

    // Date selector panel
    JPanel dateSelectorPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    dateSelectorPanel.setBackground(Color.WHITE);

    JLabel dateLabel = new JLabel("选择日期:");
    dateLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
    dateSelectorPanel.add(dateLabel);
    dateSelectorPanel.add(Box.createHorizontalStrut(10));
    dateSelectorPanel.add(dateSelector);

    // Title panel
    JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    titlePanel.setBackground(Color.WHITE);
    titlePanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 10, 0));
    titlePanel.add(titleLabel);

    topPanel.add(dateSelectorPanel, BorderLayout.NORTH);
    topPanel.add(titlePanel, BorderLayout.CENTER);

    return topPanel;
  }

  /** Create center panel with student lists 创建中央面板，包含学生列表 */
  private JPanel createCenterPanel() {
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
    centerPanel.setBackground(Color.WHITE);
    centerPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 20, 0));

    // Signed students section
    JPanel signedSection = createStudentSection("已签到学生:", signedStudentsPanel, SIGNED_BG_COLOR);

    // Unsigned students section
    JPanel unsignedSection =
        createStudentSection("未签到学生:", unsignedStudentsPanel, UNSIGNED_BG_COLOR);

    centerPanel.add(signedSection);
    centerPanel.add(Box.createVerticalStrut(10)); // Add spacing between sections
    centerPanel.add(unsignedSection);

    return centerPanel;
  }

  /** Create a student section with title and student panel 创建学生区域，包含标题和学生面板 */
  private JPanel createStudentSection(String title, JPanel studentPanel, Color backgroundColor) {
    JPanel section = new JPanel(new BorderLayout());
    section.setBackground(Color.WHITE);
    section.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));

    // Section title
    JLabel sectionTitle = new JLabel(title);
    sectionTitle.setFont(new Font("微软雅黑", Font.BOLD, 16));
    sectionTitle.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 10));

    // Student panel setup without scroll pane
    studentPanel.setBackground(backgroundColor);
    studentPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
    studentPanel.setPreferredSize(
        new Dimension(0, 150)); // Increased height to accommodate all names

    section.add(sectionTitle, BorderLayout.NORTH);
    section.add(studentPanel, BorderLayout.CENTER);

    return section;
  }

  /** Create bottom panel with statistics 创建底部面板，包含统计信息 */
  private JPanel createBottomPanel() {
    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    bottomPanel.setBackground(Color.WHITE);
    bottomPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));
    bottomPanel.add(statisticsLabel);

    return bottomPanel;
  }

  /** Setup event handlers 设置事件处理器 */
  private void setupEventHandlers() {
    dateSelector.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            loadHistoricalData();
          }
        });
  }

  /** Load historical data for selected date 加载选定日期的历史数据 */
  private void loadHistoricalData() {
    String selectedDate = (String) dateSelector.getSelectedItem();
    if (selectedDate == null) return;

    // Update title
    LocalDate date = LocalDate.parse(selectedDate);
    String formattedDate = date.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
    titleLabel.setText(formattedDate + "签到情况");

    // Get historical data for the selected date
    List<Student> studentsData = DataUtil.getHistoricalDataForDate(selectedDate);

    // Separate signed and unsigned students
    List<Student> signedStudents =
        studentsData.stream().filter(s -> s.getStatus() == 1).collect(Collectors.toList());

    List<Student> unsignedStudents =
        studentsData.stream().filter(s -> s.getStatus() == 0).collect(Collectors.toList());

    // Update student panels
    updateStudentPanel(signedStudentsPanel, signedStudents, SIGNED_TEXT_COLOR);
    updateStudentPanel(unsignedStudentsPanel, unsignedStudents, UNSIGNED_TEXT_COLOR);

    // Update statistics
    updateStatistics(studentsData.size(), signedStudents.size(), unsignedStudents.size());
  }

  /** Update student panel with student names 更新学生面板显示学生姓名 */
  private void updateStudentPanel(JPanel panel, List<Student> students, Color textColor) {
    panel.removeAll();

    // Use FlowLayout to arrange student names with proper spacing
    panel.setLayout(new FlowLayout(FlowLayout.LEFT, 15, 12));

    for (Student student : students) {
      JLabel nameLabel = new JLabel(student.getName());
      nameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
      nameLabel.setForeground(textColor);
      nameLabel.setBorder(BorderFactory.createEmptyBorder(5, 8, 5, 8));
      panel.add(nameLabel);
    }

    panel.revalidate();
    panel.repaint();
  }

  /** Update statistics display 更新统计信息显示 */
  private void updateStatistics(int total, int signed, int unsigned) {
    if (total == 0) {
      statisticsLabel.setText("当日汇总: 共0人，已签到0人，未签到0人，签到率0%");
      return;
    }

    double signRate = (double) signed / total * 100;
    String statisticsText =
        String.format("当日汇总: 共%d人，已签到%d人，未签到%d人，签到率%.1f%%", total, signed, unsigned, signRate);

    statisticsLabel.setText(statisticsText);
  }

  /** Refresh data and update display 刷新数据并更新显示 */
  public void refreshData() {
    loadHistoricalData();
  }
}
